//
//  BSContentViewController.m
//  Baisijie
//
//  Created by 王建伟 on 2017/3/14.
//  Copyright © 2017年 RangGuangyu. All rights reserved.
//

#import "BSContentViewController.h"
#import <MJRefresh.h>
#import <MJExtension.h>
#import <AFNetworking.h>
#import "BSTopicItem.h"
#import "BSTopicCell.h"
#import <SDImageCache.h>

@interface BSContentViewController ()

/** 请求管理者 */
@property (nonatomic ,strong) AFHTTPSessionManager *manager;
/** 帖子模型数组 */
@property (nonatomic ,strong) NSMutableArray <BSTopicItem *> *topics;
/** 加载开始的id */
@property (nonatomic ,copy) NSString *np;


@end

@implementation BSContentViewController

static NSString * const ID = @"BSTopicCell";

- (AFHTTPSessionManager *)manager {
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BSRGBColor(234, 234, 234, 1);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(BSTopicViewHeight - BSStatusBarHeight, 0, BSTabBarHeight, 0);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    [SVProgressHUD showWithStatus:nil];
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BSTopicCell class]) bundle:nil] forCellReuseIdentifier:ID];
    
    [BSNotificationCenter addObserver:self selector:@selector(tabBarButtonDidRepeatClick) name:BSTabBarButtonDidRepeatClickNotification object:nil];
    [BSNotificationCenter addObserver:self selector:@selector(tabBarButtonDidRepeatClick) name:BSTopicButtonDidRepeatClickNotification object:nil];
}
- (void)dealloc {
    [BSNotificationCenter removeObserver:self];
}
/**
 监听顶部标题栏按钮的重复点击通知
 */
- (void)topicButtonDidRepeatClick {
    [self tabBarButtonDidRepeatClick];
}
/**
 监听tabBarButton的重复点击通知
 */
- (void)tabBarButtonDidRepeatClick {
    //如果点击的不是精华tabBar按钮就不刷新返回
    if (self.view.window == nil) return;
    //如果是窗口不显示的控制器的view就不刷新返回
    //主窗口
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    //装换坐标系
    CGRect frame = [self.view.superview convertRect:self.view.frame toView:keyWindow];
    //两个frame是否有重叠交叉
    bool isIntersects = CGRectIntersectsRect(keyWindow.bounds, frame);
    if (isIntersects == NO) return;
    [self.tableView.mj_header beginRefreshing];
}
- (void)loadNewData {
    //取消之前的请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    NSString *urlStr = [_url stringByAppendingPathComponent:@"bs0315-iphone-4.5.5/0-20.json"];
    [self.manager GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary  *_Nullable responseObject) {
        [SVProgressHUD dismiss];
        _np = responseObject[@"info"][@"np"];
        self.topics = [BSTopicItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code != NSURLErrorCancelled) {
            [SVProgressHUD showErrorWithStatus:@"加载失败"];
        }
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)loadMoreData {
    //取消之前的请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    NSString *urlStr = [_url stringByAppendingPathComponent:[NSString stringWithFormat:@"bs0315-iphone-4.5.5/%@-20.json",_np]];
    [self.manager GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary  *_Nullable responseObject) {
        [SVProgressHUD dismiss];
        _np = responseObject[@"info"][@"np"];
        [self.topics addObjectsFromArray:[BSTopicItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]]];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code != NSURLErrorCancelled) {
            [SVProgressHUD showErrorWithStatus:@"加载失败"];
        }
        [self.tableView.mj_footer endRefreshing];
    }];
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    tableView.mj_footer.hidden = !self.topics.count;
    return self.topics.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.topics[indexPath.row].cellHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BSTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    [cell setFullTextBtnClickBlock:^(BSTopicItem *topic) {
        if (topic.showTextType == 2) {
            topic.showTextType = 1;
        } else if (topic.showTextType == 1) {
            topic.showTextType = 2;
        }
        [tableView reloadData];
    }];
    cell.topicItem = self.topics[indexPath.row];
    return cell;
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    UIPanGestureRecognizer *panGes = scrollView.panGestureRecognizer;
    CGFloat y = [panGes velocityInView:scrollView].y;
    if (y < -50) {
        //向上拖动，隐藏导航栏
        [BSNotificationCenter postNotificationName:BSScrollViewPanUpNotification object:nil];
    } else if (y > 50) {
        //向下拖动，显示导航栏
        [BSNotificationCenter postNotificationName:BSScrollViewPanDownNotification object:nil];
    } else {
        //停止拖拽
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [[SDImageCache sharedImageCache] clearMemory];
}


@end
